package com.wwdx.service.impl;

import com.google.common.collect.Maps;
import com.wwdx.model.WwdxBannerModel;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.service.WwdxBannerServiceI;
import com.wwdx.utils.ConstantHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 * @date 2017/12/2.
 */
@Service
public class WwdxBannerServiceImpl extends BaseServiceImpl<WwdxBannerModel> implements WwdxBannerServiceI {

    @Override
    public Long selectModelCount(WwdxBannerModel model) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        return count("select count(1) from WwdxBannerModel\t"+getParams(model,params),params);
    }
    
    private String getParams(WwdxBannerModel model, Map<String, Object> params){
        StringBuilder sb = new StringBuilder("where 1=1\n");
        String bannertype = model.getBannertype();
        if (StringUtils.isNotBlank(bannertype)){
            sb.append("and bannertype=:bannertype\n");
            params.put("bannertype",bannertype);
        }
        return sb.toString();
    }

    @Override
    public List<WwdxBannerModel> selectModelList(WwdxBannerModel model,Integer pageIndex, Integer pageSize) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
        return find(" from WwdxBannerModel\t"+getParams(model,params)+"\torder by gmt_created desc",params, pageIndex, pageSize);
    }

    @Override
    public List<WwdxBannerModel> banner(){
        String key = ConstantHolder.HOME_BANNER_LIST;
        List<WwdxBannerModel> bannerModels = (List<WwdxBannerModel>) valueOperations.get(key);
        if (CollectionUtils.isEmpty(bannerModels)){
            String hql = "from WwdxBannerModel where status=0 and bannertype !=13 order by sort desc";
            bannerModels = find(hql);
            bannerModels.forEach(model -> {
                WwdxBookModel wwdxBookModel = wwdxBookService.getByBookId(model.getId());
                if (wwdxBookModel != null){
                    model.setVideoauthorid(wwdxBookModel.getVideoauthorid());
                    model.setCopywriter(wwdxBookModel.getCopywriter());
                }
            });
            valueOperations.set(key,bannerModels);
        }
        return bannerModels;
    }
}